from flask import g
from flask import request
from flask import session, jsonify

from info import redis_store
from info.commons import user_login_data
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu
from flask import render_template,current_app


#功能描述
"""
访问方式：get
参数：分类编号  新闻数量

获取参数
参数类型转换，为分页做准备
获取分页数据
讲分页数据添加到字典中
返回数据

"""
@index_blu.route('/newslist')
def news_list():
    # 获取参数
    cid = request.args.get("cid",1)
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",10)
    # 参数类型转换，为分页做准备
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 获取分页数据
    try:
        #根据新闻创建时间排序
        # condition = ""
        # if cid != "1":
        #     condition = (News.category_id == cid)
        # paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
        condition = []
        if cid != "1":
            condition.append(News.category_id == cid)
        paginate = News.query.filter(*condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="获取分页数据失败")
    # 将分页数据添加到字典中
    total_pages = paginate.pages
    current_page = paginate.page
    items = paginate.items

    newsList = []
    for item in items:
        newsList.append(item.to_dict())
    # 返回数据
    print(newsList)
    return jsonify(errno=RET.OK, errmsg="获取成功",totalPage =total_pages,cur_page = current_page,newsList=newsList)

@index_blu.route('/')
@user_login_data
def index():

    # #取出session中的用户编号
    # user_id = session.get("user_id")
    # #获取用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    #将热门新闻添加到首页
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败 ")

    #将新闻对象添加到列表当中
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())

    #查询所有分类信息
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    categorys_list = []
    for category in categorys:
        categorys_list.append(category.to_dict())



    #拼接用户数据并且渲染页面
    data = {
        #如果user不为空，返回左边内容，否则返回右边内容
        "user_info":g.user.to_dict() if g.user else "",
        "click_news_list":click_news_list,
        "categorys_list":categorys_list
    }

    return render_template("news/index.html",data=data)

@index_blu.route('/favicon.ico')

def web_logo():

    return current_app.send_static_file("news/favicon.ico")
